package ufrj.devagil.timer;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;



public class TimerDeAtividadesActivity extends Activity implements OnClickListener, OnScrollListener{
    TimerdeAtividadesHelper 	bdHelper;
    ArrayList<Timer>		timers;
    long 			startTime, endTime;
    ListView 			lvTimers;
    SimpleCursorAdapter 	adapter;
    ImageButton			bAdd, bDelete, bRename;
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
	MenuInflater mi = getMenuInflater();
	mi.inflate(R.layout.menu_tela_inicial, menu);
	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
            switch (item.getItemId()) 
            {
                case R.id.statistics:
                    Toast.makeText(this, "Change to Pro Version.", Toast.LENGTH_SHORT).show();   
                    //criar e chamar funcao para gerar estatistica
                    break;
                case R.id.about:
            	    Sobre.mostrarInfo(this);
                    break;
                case R.id.exit:
                    finish();
                    break;
            }
            return true;
    }

    @Override
    public void onCreate(Bundle savedInstanceState){
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);

	bdHelper  = new TimerdeAtividadesHelper(this);
	startTime = 0;
	endTime   = 0;
	bAdd	  = (ImageButton) findViewById(R.id.botaoAddTimer);
	bRename   = (ImageButton) findViewById(R.id.botaoRenameTimer);
	bDelete   = (ImageButton) findViewById(R.id.botaoDeleteTimer);
	timers	  = bdHelper.getArrayTimers(this);
			
	bAdd.setOnClickListener(this);
	bRename.setOnClickListener(this);
	bDelete.setOnClickListener(this);
    }
    
    
    @Override
    protected void onResume() {
	super.onResume();
	setupListView();
    }

    public void setupListView(){
	String [] from = {"name", "tempoTotal"};
 	int[] 	  to   = {R.id.tvDescricao, R.id.chronometer1};
 	Cursor 	  cursor;
 	
	cursor 	= bdHelper.getTimers();
	startManagingCursor(cursor);
	
	lvTimers  = (ListView) findViewById(R.id.lvTimers);
	adapter	  = new SimpleCursorAdapter(this, R.layout.lvrowtimers, cursor, from, to);
	adapter.setViewBinder(new CustomViewBinder());
	

	lvTimers.setItemsCanFocus(true);
	lvTimers.setAdapter(adapter);
    }
    
    private class CustomViewBinder implements ViewBinder{
	public boolean setViewValue(View view, Cursor c, int columnIndex)
	{
	    if(c.getColumnIndex("tempoTotal") == columnIndex){
		Chronometer	myChronometer;
		myChronometer = (Chronometer) view;
		myChronometer.setBase(SystemClock.elapsedRealtime() - c.getInt(columnIndex));
		
		return true;
	    }
	    return false;
	}
    }

    public void onClick(View bId)
    {
	switch (bId.getId())
	{
	case R.id.botaoAddTimer:
	    showDialog();
	    break;
	case R.id.botaoRenameTimer:
	    Timer.renomear(this);
	    setupListView();
	    break;
	case R.id.botaoDeleteTimer:
	    Timer.deletar(this);
	    setupListView(); 
	    break;
	}
    }
    
    
    public void showDialog(){
	AlertDialog.Builder alert = new AlertDialog.Builder(this);

	alert.setTitle("Adding new Timer!");
	alert.setMessage("Name:");

	final EditText input = new EditText(this);
	alert.setView(input);

	alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	public void onClick(DialogInterface dialog, int whichButton) {
	    int     id;
	    String  newTimer;
	    newTimer = input.getText().toString();
	    id = bdHelper.insertTimer(newTimer);
	    timers.add(new Timer(id, newTimer, TimerDeAtividadesActivity.this));
	    setupListView();
	  }
	});
	
	alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	  public void onClick(DialogInterface dialog, int whichButton) {
	     dialog.cancel();
	  }
	});

	alert.show();
    }

    public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
	// TODO Auto-generated method stub
	
    }

    public void onScrollStateChanged(AbsListView view, int scrollState) {
	// TODO Auto-generated method stub
	
    }

    public void myClickHandler(View v){
	LinearLayout 	linearLayout;
	TextView 	timerDescription;
	ImageButton	b;
	Timer 	      	t;
	
	t 	         = null;
	linearLayout     = (LinearLayout)v.getParent();
	b		 = (ImageButton)linearLayout.getChildAt(0);
	timerDescription = (TextView)linearLayout.getChildAt(1);
	
	
	 
	for(int i=0; i<timers.size(); i++){
	    if (timers.get(i).description.equals(timerDescription.getText().toString())){
		t 		= timers.get(i);
		t.myChronometer = (Chronometer) linearLayout.getChildAt(2);
		break;
	     }
	 }
	 
	   
	 if (t.isRunning){
     
	     t.isRunning = false;
	     t.myChronometer.stop();
	     b.setImageResource(R.drawable.play);
	
	     t.seasonEnd   =  SystemClock.elapsedRealtime();
	     t.tempoTotal  = t.tempoTotal + (t.seasonEnd - t.seasonStart);
	     	     
	     bdHelper.insertHistory(t.id, t.seasonEnd - t.seasonStart, t.seasonStart);
	     t.seasonStart = t.seasonEnd = 0;
	 }
	 else{
	     t.isRunning = true;
	     b.setImageResource(R.drawable.stop);
	     
	     t.myChronometer.setBase(SystemClock.elapsedRealtime() - t.tempoTotal);
	     t.myChronometer.start();
	     t.seasonStart = SystemClock.elapsedRealtime();
	 }

	 linearLayout.refreshDrawableState();
    }
    

}
